package com.aef.controller;

import java.math.BigDecimal;
import java.util.Date;

import com.aef.model.TdRecycle;
import com.aef.service.RecycleService;
import com.aef.service.WeixinUserService;
import com.aef.utils.DateUtils;
import com.aef.utils.IdWorker;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.PropKit;
import com.jfinal.weixin.sdk.api.AccessTokenApi;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.SnsAccessToken;
import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;

public class SalesmanController extends WeixinMsgController{
	private static String appid = PropKit.get("appId");
    private static String secret = PropKit.get("appSecret");
    private static String redirect_uri=PropKit.get("domain")+"salesman/getList";
    RecycleService recycleService=new RecycleService();
    WeixinUserService weixinUserService=new WeixinUserService();
    public void index() {
		redirect(SnsAccessTokenApi.getAuthorizeURL(appid,redirect_uri,false));
	}
	
	public void getList() {
		ApiConfigKit apiConfigKit=new ApiConfigKit();
		apiConfigKit.setThreadLocalApiConfig(getApiConfig());
		AccessTokenApi accesstokenapi=new AccessTokenApi();
		String code=getPara("code");
		System.out.println("code:"+code);
        SnsAccessToken snsAccessToken=SnsAccessTokenApi.getSnsAccessToken(appid, secret, code);
        String openid=snsAccessToken.getOpenid();
		System.out.println("openid"+openid);
		setAttr("openid", openid);
		renderJsp("/salesman/index.jsp");
	}

	public void JudgeOpenidbund(){
		String openid=getPara("openid");
		renderJson(recycleService.JudgeOpenidbund(openid));
	}
	public void recycle() throws Exception{
		String openid=getPara("openid");
		int companyid=Integer.parseInt(getPara("companyid"));
		BigDecimal declare_number=new BigDecimal(getPara("declare_number"));
		Date time=DateUtils.getStrSwitchData(getPara("time"));
		TdRecycle recycle=new TdRecycle();
		recycle.setOpenid(openid);
		recycle.setCompanyid(companyid);
		recycle.setDeclareNumber(declare_number);
		recycle.setTime(time);
		IdWorker iw1 = new IdWorker(1);
		recycle.setDanhao(String.valueOf(iw1.nextId()));
		boolean recycletype=recycleService.recycle(recycle);
		JSONObject json=new JSONObject();
		if(recycletype){
			json.put("errorcode", "0");
			json.put("value", "添加成功");
		}else{
			json.put("errorcode", "1");
			json.put("value", "添加失败");
		}
		renderJson(json);
	}
}
